<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
<head>
  <title>Title</title>
  <link rel="stylesheet" href="/static/layui/css/layui.css">
  <style>
    .order-item-container {
      padding: 20px;
    }
    .order-item-field {
      margin-bottom: 15px;
      display: flex;
      align-items: center;
    }
    .order-item-field label {
      width: 100px;
      font-weight: bold;
    }
    .order-item-field img {
      margin-left: 10px;
    }
  </style>
</head>
<body>
<form class="layui-form">
  订单编号：
  <div class="layui-inline">
    <input type="text" name="orderNo" class="layui-input" lay-affix="clear">
  </div>
  用户id：
  <div class="layui-inline">
    <input type="text" name="userId" class="layui-input" lay-affix="clear">
  </div>
  创建开始时间:
  <div class="layui-inline">
    <input type="text" class="layui-input" name="beginCreateTime" id="beginCreateTime" placeholder="yyyy-MM-dd">
  </div>
  创建结束时间:
  <div class="layui-inline">
    <input type="text" class="layui-input" name="endCreateTime" id="endCreateTime" placeholder="yyyy-MM-dd">
  </div>
  <div class="layui-inline">
    <button class="layui-btn" lay-submit lay-filter="submitSearch">搜索</button>
    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
  </div>
</form>

<table class="layui-hide" id="tableId" lay-filter="tableId"></table>

<script type="text/html" id="toolDemo">
  <div class="layui-clear-space">
    <a class="layui-btn layui-btn-xs" lay-event="shipping">发货</a>
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="deleteById">删除</a>
    <a class="layui-btn layui-btn-xs layui-btn-primary" lay-event="content">详情</a>
  </div>
</script>

<button lay-options="{accept: 'file'}" id="importExcel"></button>
<script type="text/html" id="toolbarDemo">
  <div class="layui-btn-container">
    <button class="layui-btn layui-btn-sm" lay-event="add">添加</button>
    <button class="layui-btn layui-btn-sm" lay-event="deleteAll">批量删除</button>
  </div>
</script>

<script type="text/html" id="imageTemplet">
  <img src="{{d.mainImage}}"/>
</script>

<script type="text/html" id="payTemplet">
  {{#    if(d.paymentType==0){    }}
  <span>货到付款</span>
  {{#     }else if(d.paymentType==1){          }}
  <span class="layui-bg-green">微信</span>
  {{#     }else if(d.paymentType==2){          }}
  <span class="layui-bg-blue">支付宝</span>
  {{#     }else if(d.paymentType==3){          }}
  <span class="layui-bg-red">银联</span>
  {{#    }                   }}
</script>

<script type="text/html" id="statusTemplet">
  {{#    if(d.status==0){    }}
  <span>订单已取消</span>
  {{#     }else if(d.status==1){          }}
  <span class="layui-bg-red">未付款</span>
  {{#     }else if(d.status==2){          }}
  <span class="layui-bg-green">已付款</span>
  {{#     }else if(d.status==3){          }}
  <span class="layui-bg-blue">已发货</span>
  {{#     }else if(d.status==4){          }}
  <span class="layui-bg-green">交易完成</span>
  {{#     }else if(d.status==5){          }}
  <span class="layui-bg-green">交易已关闭</span>
  {{#    }                   }}
</script>

<!--<script type="text/html" id="statusTemplet1">-->
<!--    <input type="checkbox" name="status" value="{{= d.id }}" lay-text="激活|禁用" lay-skin="switch" lay-filter="statusFilter" {{d.status == 1 ? "checked" : "" }}>-->
<!--</script>-->

<script src="/static/jquery-2.1.4.js" type="text/javascript" charset="utf-8"></script>
<script src="/static/layui/layui.js" type="text/javascript" charset="utf-8"></script>
<script src="/static/mylayer.js" type="text/javascript" charset="utf-8"></script>
<script>
  layui.use(['table','layer', 'form', 'upload', 'laydate'], function(){
    var table = layui.table;
    var layer = layui.layer;
    var form = layui.form;
    var upload = layui.upload;
    var laydate = layui.laydate;
    // 渲染
    laydate.render({
      elem: '#beginCreateTime',
      type: 'datetime'
    });
    laydate.render({
      elem: '#endCreateTime',
      type: 'datetime'
    });

    // 状态 - 开关操作
    form.on('switch(statusFilter)', function(obj){
      var id = this.value;
      var checked = obj.elem.checked;
      var status = checked ? 1 : 0;
      $.post(
              '/order/updateStatus',
              {'id': id, 'status': status},
              function (result) {
                console.log(result);
              },
              'json'
      );
    });

    // 渲染
    upload.render({
      elem: '#importExcel', // 绑定多个元素
      url: '/order?method=importExcel', // 此处配置你自己的上传接口即可
      accept: 'file', // 普通文件
      done: function(res){
        layer.msg('上传成功');
        console.log(res);
      }
    });

    table.render({
      elem: '#tableId',
      url:'/order/list',
      toolbar: '#toolbarDemo',
      cols: [
        [
          {type: 'checkbox', fixed: 'left'},
          {field:'orderNo', title: '订单号', sort: true},
          {field:'userId', title: '用户Id'},
          {field:'shippingId', title: '购物车Id'},
          {field:'payment', title: '支付金额'},
          {field:'paymentType', title: '付款方式',templet: '#payTemplet'},
          {field:'status', title: '状态',templet:'#statusTemplet'},
          {field:'createTime', title: '创建时间'},
          {fixed: 'right', title:'操作', width: 134, minWidth: 125, templet: '#toolDemo'}
        ]
      ],
      page: true
    });

    // 搜索提交
    form.on('submit(submitSearch)', function(data){

      var field = data.field; // 获得表单字段
      // 执行搜索重载
      //http://localhost:8081/order?method=selectByPage&page=1&limit=10&name=Java&credit=3
      table.reload('tableId', {
        page: {
          curr: 1 // 重新从第 1 页开始
        },
        where: field // 搜索的字段
      });

      return false; // 阻止默认 form 跳转
    });

    // 触发单元格工具事件
    table.on('tool(tableId)', function(obj){ // 双击 toolDouble
      var data = obj.data; // 获得当前行数据
      // {id:12,name:'Java',credit:3}
      console.log(data);
      // console.log(obj)
      if(obj.event === 'update'){
        layer.open({
          type: 2,
          title: '编辑数据',
          area: ['90%', '90%'],
          content: '/page/order/update?id=' + data.id
        });
      } else if(obj.event === 'deleteById'){
        layer.confirm('您确认要删除么?', function () {
          $.post(
                  '/order/deleteById',
                  {'id': data.id},
                  function (result) {
                    console.log(result);
                    if (result.code == 0) {
                      mylayer.okMsg(result.msg);
                      //删除数据之后刷新表格，展示最新数据
                      table.reload('tableId');
                    } else {
                      mylayer.errorMsg(result.msg);
                    }
                  },
                  'json'
          );
        });
      } else if (obj.event == 'content') {
        // 使用AJAX请求获取/orderItem的内容
        $.ajax({
          url: '/order/orderItem', // 确保URL正确
          type: 'POST',
          data: {
            orderNo: data.orderNo // 假设data中包含orderNo
          },
          success: function(response) {
            // 请求成功后，解析返回的JSON数据
            const orderItems = response.data; // 假设返回的JSON结构是 { code: 0, data: [OrderItem1, OrderItem2, ...] }

            // 动态生成HTML内容
            let html = '';
            orderItems.forEach(item => {
              html += `
                    <div class="order-item-container">
                        <h3>订单详情</h3>
                        <div class="order-item-field">
                            <label>订单编号：</label>
                            <span>${item.orderNo}</span>
                        </div>
                        <div class="order-item-field">
                            <label>产品名称：</label>
                            <span>${item.productName}</span>
                        </div>
                        <div class="order-item-field">
                            <label>产品图片：</label>
                            <img src="${item.productImage}" alt="产品图片" style="max-width: 100px; max-height: 100px;">
                        </div>
                        <div class="order-item-field">
                            <label>单价：</label>
                            <span>${item.currentUnitPrice}</span>
                        </div>
                        <div class="order-item-field">
                            <label>数量：</label>
                            <span>${item.quantity}</span>
                        </div>
                        <div class="order-item-field">
                            <label>总价：</label>
                            <span>${item.totalPrice}</span>
                        </div>
                        <div class="order-item-field">
                            <label>状态：</label>
                            <span>${item.status}</span>
                        </div>
                    </div>
                `;
            });

            // 将生成的HTML内容插入到页面中
            $('#orderDetailsContainer').html(html);

            // 使用生成的HTML内容打开layer窗口
            layer.open({
              type: 1,
              title: data.name,
              area: ['90%', '90%'],
              content: html
            });
          },
          error: function() {
            // 请求失败时的处理
            layer.msg('获取订单信息失败，请稍后再试！');
          }
        });
      }
      else if (obj.event == 'shipping'){
        layer.confirm('您确认发货吗?', function () {
          $.post(
             '/order/shipping',
                  {'orderNo':data.orderNo,'status': data.status},
                  function (result){
                      console.log(result);
                      if(result.code == 0){
                        mylayer.okMsg(result.msg);
                        table.reload('tableId');
                      }else{
                        mylayer.errorMsg();
                      }
                  }
                  ,'json'
          )
        })
      }
    });
    // 头部工具栏事件
    table.on('toolbar(tableId)', function(obj){
      var options = obj.config; // 获取当前表格属性配置项
      var checkStatus = table.checkStatus(options.id); // 获取选中行相关数据
      console.log(obj); // 查看对象所有成员


      // 根据不同的事件名进行相应的操作
      switch(obj.event){ // 对应模板元素中的 lay-event 属性值
        case 'exportExcel':
          location.href = '/order?method=exportExcel';
          break;
        case "importExcel":
          $('#importExcel').click();
          break
        case 'add':
          layer.open({
            type: 2,
            title: '添加数据',
            area: ['90%', '90%'],
            content: '/page/order/add'
          });
          break;
        case 'deleteAll':
          var data = checkStatus.data;
          //[{id: 1, name: 'Java', credit: 5}, {…}]
          var ids = new Array();
          $(data).each(function () {
            ids.push(this.id);
          })
          //[2,3]
          layer.confirm('您确认要删除么?', function () {
            $.post(
                    '/order/deleteAll',
                    {field: data.field},
                    function (result) {
                      console.log(result);
                      if (result.code == 0) {
                        mylayer.okMsg(result.msg);
                        //删除数据之后刷新表格，展示最新数据
                        table.reload('tableId');
                      } else {
                        mylayer.errorMsg(result.msg);
                      }
                    },
                    'json'
            );
          });
          break;
      }
    });

  });
</script>
</body>
</html>